import { _decorator, Component, Node, Vec3, Layers } from 'cc';
import { GlobalEventBus } from '../core/EventBus';
import { EnemyRegistry } from './EnemyRegistry';
import { generateId } from '../util/Id';
import { track } from '../telemetry/Track';
import { EntityIndex } from '../world/EntityIndex';

const { ccclass, property } = _decorator;

@ccclass('EnemyDummy')
export class EnemyDummy extends Component {
  @property
  public enemyId = '';

  @property
  public threatLevel = 0.5;

  @property
  public maxHealth = 100;

  private currentHealth = 0;
  private unsubscribeHit: (() => void) | null = null;

  get id(): string {
    return this.enemyId;
  }

  get position(): Vec3 {
    return this.node.worldPosition.clone();
  }

  onLoad() {
    // Layer fallback: ensure enemies are rendered by default camera
    this.node.layer = Layers.Enum.DEFAULT;
    if (typeof console !== 'undefined' && console.debug) {
      console.debug('[LAYER] set DEFAULT for', this.node.name);
    }
    EntityIndex.addEnemy(this.node);
    if (typeof console !== 'undefined' && console.debug) {
      console.debug('[ENEMY] add', this.node.uuid);
    }
  }

  onEnable() {
    if (!this.enemyId) {
      this.enemyId = generateId();
    }
    this.currentHealth = this.maxHealth;
    EnemyRegistry.register(this.enemyId, this);
    GlobalEventBus.emit('entity/spawn', {
      id: this.enemyId,
      kind: 'enemy',
    });
    this.unsubscribeHit = GlobalEventBus.on('combat/hit', this._onHit);
  }

  onDisable() {
    EnemyRegistry.unregister(this.enemyId);
    this.unsubscribeHit?.();
    this.unsubscribeHit = null;
    this.unscheduleAllCallbacks();
  }

  private _onHit = (payload: { src: string; dst: string; dmg: number; isCrit: boolean; pierceLeft: number }) => {
    if (payload.dst !== this.enemyId) {
      return;
    }
    this.currentHealth -= payload.dmg;
    track('enemy_hit', { id: this.enemyId, dmg: payload.dmg, hpLeft: this.currentHealth });
    if (this.currentHealth <= 0) {
      GlobalEventBus.emit('entity/die', {
        id: this.enemyId,
        killer: payload.src,
      });
      track('enemy_dead', { id: this.enemyId, killer: payload.src });
      this.node.destroy();
    }
  };

  onDestroy() {
    EntityIndex.removeEnemy(this.node);
  }
}
